package com.yangchoi.jetpackcompose.ui.widget.component

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.ceil

/**
 * 通用gridview，解决组合column使用滑动冲突的问题
 * @param dataList 数据集合
 * @param columnCount 每一行多少个
 * @param itemHeight item高度,用来计算整个gridview的高度
 * @param itemContent item内容
 * @param defaultMoreHeight 扩展高度,如果出现item加载不完的情况，可以传入数值让gridview更高
 * @param userScrollEnabled 是否开启gridview本身自己的滑动
 */
@Composable
fun <T> CommonVerticalGrid(
    dataList:ArrayList<T>,
    columnCount:Int,
    itemHeight:Int,
    defaultMoreHeight:Int = 20,
    horizontalDp: Dp = 16.dp,
    verticalDp: Dp = 8.dp,
    userScrollEnabled:Boolean = false,
    itemContent:@Composable (index:Int, item:T)->Unit,
){
    BoxWithConstraints {
        val itemCount = dataList.size
        val rowCount = ceil(itemCount.toFloat() / columnCount).toInt()
        LazyVerticalGrid(
            columns = GridCells.Fixed(columnCount),
            contentPadding = PaddingValues(horizontalDp, verticalDp),
            userScrollEnabled = userScrollEnabled,
            content = {
                itemsIndexed(dataList){index, item ->
                    Box(
                        Modifier
                            .height(itemHeight.dp)
                            .padding(4.dp)
                    ) {
                        itemContent(index,item)
                    }
                }
            },
            modifier = Modifier.height((itemHeight * rowCount + defaultMoreHeight).dp)
        )
    }
}